# cython: language_level=3
import os

from dotenv import load_dotenv
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.operator import Operator
from common.database import get_db

load_dotenv()
CREDIT_CODE = os.getenv("CREDIT_CODE")
USER_NAME = os.getenv("USER_NAME")
OPERATOR = os.getenv("OPERATOR")


def get_operator_by_credit_code(db: Session, credit_code: str):
    ret_data = []

    if credit_code != CREDIT_CODE:
        return None

    results = db.scalars(select(Operator)).all()
    for result in results:
        ret_data.append(
            {
                "creditCode": result.credit_code,
                "userName": result.user_name,
                "operator": result.operator,
                "operatorTel1": result.operator_tel1,
                "operatorTel2": result.operator_tel2 if result.operator_tel2 else "",
                "operatorAddress": result.operator_address,
            }
        )
    return ret_data


def init_operator():
    db = next(get_db())
    first_operator = db.scalars(select(Operator)).first()
    if first_operator:
        return first_operator
    operator = Operator(
        credit_code=CREDIT_CODE,
        user_name=USER_NAME,
        annual_electricity_consumption=0,
        electricity_consumption_char="",
        operator=OPERATOR,
        operator_tel1="123123123123",
        operator_tel2="123123123123",
        operator_address="test",
        operator_remark="test",
    )
    db.add(operator)
    db.commit()
    db.refresh(operator)
    return operator
